package com.edu.atams.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.atams.common.dto.PersonInfomationDto;
import com.edu.atams.common.dto.SelectClassDto;
import com.edu.atams.common.lang.Result;
import com.edu.atams.entity.*;
import com.edu.atams.entity.Class;
import com.edu.atams.mapper.*;
import com.edu.atams.service.ClassService;
import com.edu.atams.service.ClassSubjectService;
import com.edu.atams.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author czj666
 * @since 2021-10-09
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController extends BaseController {

    @Autowired
    TeacherMapper teacherMapper;

    @Autowired
    StudentParentMapper studentParentMapper;

    @Autowired
    StudentClassMapper studentClassMapper;

    @Autowired
    ClassSubjectMapper classSubjectMapper;

    @Autowired
    ClassSubjectService classSubjectService;
    @Autowired
    ClassService classService;
    @Autowired
    GradeService gradeService;

    @GetMapping("/listClasses")
    public Result listClasses(){
        String username = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("user_id", sysUser.getId()));
        List<ClassSubject> classSubjects = classSubjectService.list(new QueryWrapper<ClassSubject>().eq("teacher_id", teacher.getId()));
        classSubjects.forEach(classSubject -> {
            classSubject.setMyClass(classService.getById(classSubject.getClassId()));
            classSubject.getMyClass().setGrade(gradeService.getById(classSubject.getMyClass().getGradeId()));
        });
        return Result.succ(classSubjects);
    }

    @GetMapping("/listall")
    public Result listAll(){
        List<Teacher> teachers =teacherService.list();
        return Result.succ(teachers);
    }
    @GetMapping("/list")
    public Result list(String name,String schoolno){
        Page<Teacher> teacherPage=teacherService.page(getPage(),
                new QueryWrapper<Teacher>().
                        like(StrUtil.isNotBlank(name),"name",name)
                        .like(StrUtil.isNotBlank(schoolno),"schoolNo",schoolno)
        );
        return Result.succ(teacherPage);
    }
    @PostMapping("/save")
    public Result save(@RequestBody Teacher teacher){
        String schoolNo="";
        do{
            schoolNo= RandomUtil.randomNumbers(6);
        }while(teacherService.count(new QueryWrapper<Teacher>().eq("schoolNo",schoolNo))!=0);
        teacher.setSchoolno(schoolNo);
        teacherService.save(teacher);
        SysUser sysUser=new SysUser();
        sysUser.setUsername(teacher.getSchoolno());
        String password = bCryptPasswordEncoder.encode("123456");
        sysUser.setPassword(password);
        sysUser.setRoleType(2);
        sysUserService.save(sysUser);
        Integer id=sysUser.getId();
        teacher.setUserId(id);
        return Result.succ(teacherService.updateById(teacher));
    }
    @PostMapping("/delete")
    public Result delete(@RequestBody Integer[] ids){
        List<String> teacherSchools=teacherMapper.getTeacherUsernameByIds(ids);
        teacherService.removeByIds(Arrays.asList(ids));
        teacherSchools.toArray();
        System.out.println(teacherSchools);
        sysUserService.remove(new QueryWrapper<SysUser>().in("username",teacherSchools));
        return Result.succ("");
    }
    @PostMapping("/update")
    public Result update(@RequestBody Teacher teacher){
        teacherService.updateById(teacher);
        return Result.succ(teacher);
    }
    @PostMapping("/upload")
    public Result upload(@RequestParam("excel") MultipartFile excel) throws IOException {
        return teacherService.excelUpload(excel);
    }

    //根据 老师Id 获取该没有任课过的学年的年级班级
    @GetMapping("/getClassList/{id}")
    public Result getClassList(@PathVariable("id") Integer id){
        return Result.succ(classService.getClassList(id));
    }

    //老师加入班级
    @PostMapping("/addClassByTeacherId/{id}")
    public  Result addclass(@PathVariable("id") Integer id,@RequestParam List<Integer> ids){

        List<ClassSubject> classSubjects=new ArrayList<>();
        for (Integer classId : ids) {
            ClassSubject classSubject=new ClassSubject();
            classSubject.setClassId(classId);
            classSubject.setTeacherId(id);
            classSubject.setSubjectId(null);
            classSubjects.add(classSubject);
        }
        return Result.succ(classSubjectService.saveBatch(classSubjects));
    }



    @GetMapping("/getclassinfomation/{id}")
    public Result getclassinfomation(@PathVariable("id") Integer teacherid){
        //根据teacherid查询所教的所有课程--班级
        List<ClassSubject>  classSubjectList=classSubjectService.list(new QueryWrapper<ClassSubject>().in("teacher_id",teacherid));
        //查询所教的所有班级id
        List<Integer> classids=classSubjectList.stream().map(ClassSubject::getClassId).collect(Collectors.toList());
        List<Class> classList=classService.listByIds(classids);
        List<SelectClassDto> selectClassDtos=new ArrayList<>();


        for (Class aClass : classList) {
            SelectClassDto selectClassDto=new SelectClassDto();
            selectClassDto.setId(aClass.getId());
            Grade grade=gradeService.getOne(new QueryWrapper<Grade>().eq("id",aClass.getGradeId()));
            aClass.setGrade(grade);
            selectClassDto.setName(grade.getYear()+aClass.getGrade().getName()+aClass.getName());

            List<StudentClass> studentClasses=studentClassService.list(new QueryWrapper<StudentClass>().eq("class_id",aClass.getId()));
            selectClassDto.setStudentNum(studentClasses.size());

            List<Integer> studentIds=studentClasses.stream().map(StudentClass::getStudentId).collect(Collectors.toList());

            if(studentIds.size()==0){
                selectClassDto.setParentNum(0);
            }else {
                List<StudentParent> studentParents=studentParentService.list(new QueryWrapper<StudentParent>().in("student_id",studentIds));
                selectClassDto.setParentNum(studentParents.size());
            }

            List<ClassSubject> classSubjects=classSubjectService.list(new QueryWrapper<ClassSubject>().eq("class_id",aClass.getId()));
            selectClassDto.setTeacherNum(classSubjects.size());
            selectClassDtos.add(selectClassDto);
        }
        return Result.succ(selectClassDtos);
    }

    @GetMapping("/getpersoninfomation/{id}")
    public Result getpersoninfomation(@PathVariable("id") Integer classId){
        //存储返回前段的Listdto对象
        List<PersonInfomationDto> personInfomationDtos=new ArrayList<>();
        //存储不同角色对象要返回的信息
        PersonInfomationDto teacherinformation=new PersonInfomationDto();
        PersonInfomationDto studentinformation=new PersonInfomationDto();
        PersonInfomationDto parentinformation=new PersonInfomationDto();
        //教师信息
        List<Integer> teacherids=classSubjectService.list(new QueryWrapper<ClassSubject>().in("class_id",classId)).stream().map(ClassSubject::getTeacherId).collect(Collectors.toList());
        if(teacherids.size()!=0) {
            List<Teacher> teachers = teacherService.listByIds(teacherids);
            List<PersonInfomation> teacherinfomations = new ArrayList<>();
            for (Teacher teacher : teachers) {
                PersonInfomation personInfomation = new PersonInfomation();
                BeanUtil.copyProperties(teacher, personInfomation);
                teacherinfomations.add(personInfomation);
            }
            teacherinformation.setType("教师");
            teacherinformation.setPersonInfomations(teacherinfomations);
        }else{
            teacherinformation.setType("教师");
            teacherinformation.setPersonInfomations(null);
        }
        personInfomationDtos.add(teacherinformation);
        //学生信息
        List<Integer> studentids= studentClassService.list(new QueryWrapper<StudentClass>().in("class_id",classId)).stream().map(StudentClass::getStudentId).collect(Collectors.toList());
        if(studentids.size()!=0) {
            List<Student> students = studentService.listByIds(studentids);
            List<PersonInfomation> studentinformations = new ArrayList<>();
            for (Student student : students) {
                PersonInfomation personInfomation = new PersonInfomation();
                BeanUtil.copyProperties(student, personInfomation);
                studentinformations.add(personInfomation);
            }
            studentinformation.setType("学生");
            studentinformation.setPersonInfomations(studentinformations);
        }else{
            studentinformation.setType("学生");
            studentinformation.setPersonInfomations(null);
        }
        personInfomationDtos.add(studentinformation);
        System.out.println(studentids);
        //家长信息
        //判断根据class查询出来的学生id是否为空，如果为空，在查询studentparent表时会查询空数据，系统会报错
        if(studentids.size()!=0) {
            List<Integer> parentids = studentParentService.list(new QueryWrapper<StudentParent>().in("student_id", studentids)).stream().map(StudentParent::getParentId).collect(Collectors.toList());
            if (parentids.size() != 0) {
                List<Parent> parents = parentService.listByIds(parentids);
                List<PersonInfomation> parentinfomations = new ArrayList<>();
                for (Parent parent : parents) {
                    PersonInfomation personInfomation = new PersonInfomation();
                    BeanUtil.copyProperties(parent, personInfomation);
                    parentinfomations.add(personInfomation);
                }
                parentinformation.setType("家长");
                parentinformation.setPersonInfomations(parentinfomations);
            } else {
                parentinformation.setType("家长");
                parentinformation.setPersonInfomations(null);
            }
        }else{
            parentinformation.setType("家长");
            parentinformation.setPersonInfomations(null);
        }
        personInfomationDtos.add(parentinformation);
        return Result.succ(personInfomationDtos);
    }
}
